<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/09/07
 * Time: 13:29
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\wms;

use app\admin\controller\BaseController;
use app\common\model\Warehouse;
use app\common\service\product\WarehouseService;
use think\facade\Validate;

class WarehouseController extends BaseController
{
    public function index()
    {
        if($this->request->isAjax())
        {
            $warehouse = Warehouse::order("is_default desc,warehouse_id desc")->select();
            $this->assign("list", $warehouse);
            return $this->fetch("lists");
        }
        return $this->fetch("index");
    }

    /**
     * 获取仓库信息
     * @date 2020/09/14
     * @author longli
     */
    public function get()
    {
       $id = $this->request->get("warehouse_id");
       if(empty($id)) return apiResponse(\app\common\status\BaseStatus::CODE_FAULT, [], '非法请求');
       return apiResponse(\app\common\status\BaseStatus::CODE_NORMAL, Warehouse::get($id)->toArray(), '获取成功');
    }

    /**
     * 添加仓库
     * @date 2020/09/14
     * @author longli
     */
    public function add()
    {
        $wid = $this->request->request('warehouse_id');
        if(!empty($wid)) $this->assign('warehouse', Warehouse::get($wid));
        return $this->fetch('add');
    }

    /**
     * 更新仓库信息
     * @date 2020/09/14
     * @author longli
     */
    public function save()
    {
        if($this->request->isPost())
        {
            $validate = Validate::make([
                'name'  => 'require',
                'area'  => 'egt:0',
            ],[
                'name.require' => '仓库名称必填',
                'area.egt' => '仓库面积无效',
            ]);
            $data = $this->request->post();
            if(!$validate->batch()->check($data))$this->error(join(', ', $validate->getError()));
            if(!isset($data['status'])) $data['status'] = Warehouse::IS_NO;
            if(!isset($data['is_virtual'])) $data['is_virtual'] = Warehouse::IS_NO;
            if(!isset($data['is_default'])) $data['is_default'] = Warehouse::IS_NO;
        }
        else
        {
            $validate = Validate::make([
                'warehouse_id'  => 'require',
            ],[
                'warehouse_id.require' => '非法请求',
            ]);
            $data = $this->request->only(['warehouse_id', 'status', 'is_default', 'is_virtual'], 'get');
            if(!$validate->batch()->check($data))$this->error(join(', ', $validate->getError()));
        }
        WarehouseService::getInstance()->addWarehouse($data)
            ? $this->success('操作成功')
            : $this->error('操作失败');
    }

    /**
     * 删除仓库
     * @date 2020/09/14
     * @author longli
     */
    public function delete()
    {
        $warehouseId = $this->request->request("ids");
        if(empty($warehouseId)) $this->error('参数错误');
        Warehouse::destroy($warehouseId);
        $this->success('删除成功');
    }
}